import React, {Component} from 'react';
import Dialog from 'material-ui/Dialog';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import CircularProgress from 'material-ui/CircularProgress';

import CONFIG from '../config';
import { errorHandle } from './Utils/ErrorHandle';
import { checkHttpStatus, parseJSON, postJsonMethod } from '../redux/Helper';

export default class Home extends Component {
  state = {
    isFetching: false,
    detail: '',
    error: null
  };

  /**
   * 保存detail
   */
  handleChangeText = (n, e, v) => {
    this.setState({[n]: v})
  };

  /**
   * 提交反馈数据
   */
  post = () => {
    if (this.state.detail != '') {
      let url = `${CONFIG.apiHost}/api/feedback?token=${this.props.token}`;

      let data = {
        user_id: this.props.userId,
        detail: this.state.detail
      };

      this.setState({isFetching: true});

      fetch(url, postJsonMethod(data))
      .then(checkHttpStatus)
      .then(parseJSON)
      .then(res => {
        this.setState({isFetching: false});
        this.props.handleOpenSnackbar('已提交，感谢你的反馈！');
        this.close();
      })
      .catch(e => {
        Promise.resolve(e.res.json()).then(v => {
          this.setState({isFetching: false, error: v.msg});
          if (v.error) {
            this.props.tokenExpired();
          }
        })
      })
    }
  };

  /**
   * 关闭时初始化数据
   */
  close = () => {
    this.setState({
      isFetching: false,
      detail: '',
      error: null
    });

    this.props.handleClose('openFeedback');
  };

  render() {
    const actions = [
      <FlatButton
        label="取消"
        primary={true}
        onTouchTap={this.close}
      />,
      <div className="pull-right" style={{width: 88}}>
        {this.state.isFetching ? 
          <CircularProgress 
            style={{margin: 6, marginLeft: 32, marginRight: 32}}
            size={24}
          />
        : 
          <FlatButton
            label="提交"
            primary={true}
            onTouchTap={this.post}
          />
        }
      </div>
    ];

  	return (
  	  <Dialog
        actions={actions}
        modal={false}
        open={this.props.open}
        onRequestClose={this.close}
        overlayStyle={{backgroundColor: 'rgba(0,0,0,0.12)'}}
        contentStyle={{width: '100%', maxWidth: 480}}
        bodyStyle={{paddingTop: 0}}
      >
        <TextField
          hintText="提宝贵意见或在此写下您遇到的问题，谢谢"
          floatingLabelText="建议或问题反馈"
          multiLine={true}
          fullWidth={true}
          rows={5}
          defaultValue={this.state.detail}
          onChange={this.handleChangeText.bind(this, 'detail')}
          errorText={errorHandle(this.state.error, 'detail')}
        /><br />
        <p>或访问项目作者的<a href="http://author.imlooke.com" target="_blank">个人主页</a></p>
      </Dialog>
  	);
  }
};